package com.omega.encryptedsql.utils;

/**
 * @author omega
 * @description: TODO
 * @date 2025/7/10
 */
import java.security.SecureRandom;
import java.util.Base64;

public class KeyGeneratorUtil {

    /**
     * 生成指定长度的随机密钥
     * @param bits 密钥位数（128, 192, 256）
     * @return Base64编码的密钥
     */
    public static String generateRandomKey(int bits) {
        if (bits != 128 && bits != 192 && bits != 256) {
            throw new IllegalArgumentException("Invalid key length. Must be 128, 192 or 256 bits");
        }

        int bytes = bits / 8;
        byte[] key = new byte[bytes];
        new SecureRandom().nextBytes(key);
        return Base64.getEncoder().encodeToString(key);
    }

    /**
     * 生成人类可读的随机密钥
     * @param bits 密钥位数（128, 192, 256）
     * @return 可读的密钥字符串
     */
    public static String generateHumanReadableKey(int bits) {
        if (bits != 128 && bits != 192 && bits != 256) {
            throw new IllegalArgumentException("Invalid key length. Must be 128, 192 or 256 bits");
        }

        int chars = bits / 8;
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
        StringBuilder sb = new StringBuilder();
        SecureRandom random = new SecureRandom();

        for (int i = 0; i < chars; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println("128-bit Key (Base64): " + generateRandomKey(128));
        System.out.println("256-bit Human Readable Key: " + generateHumanReadableKey(256));
    }
}
